package eerbaar.server.serializer.internal;

import javax.xml.stream.XMLStreamException;

import eerbaar.shared.exceptions.GameException;
import eerbaar.shared.persist.IPersistService;
import eerbaar.shared.persist.IPersister;
import eerbaar.shared.persist.ISerializerService;
import eerbaar.shared.service.ServiceFactory;
import eerbaar.shared.tree.INode;
import eerbaar.shared.tree.INodeXMLConverter;

public class ServerSerializerService {

    public static class Service implements ISerializerService,
            INodeXMLConverter {

        @Override
        public INode convertToNode(String inData) throws GameException {
            assert (inData != null);

            try {
                return new ConvertToNode().convert(inData);
            } catch (XMLStreamException e) {
                e.printStackTrace();
                throw new GameException(e);
            }
        }

        @Override
        public String convertToXml(INode inNode) throws GameException {
            assert (inNode != null);

            return new ConvertToXml().convert(inNode);
        }

        @Override
        public <T> T load(Class<T> type, String data) throws GameException {

            INodeXMLConverter converter = new ServerConverter();
            INode node = converter.convertToNode(data);

            IPersistService service = ServiceFactory
                    .getService(IPersistService.class);
            return service.load(type, node);
        }

        @Override
        public <T> String save(Class<T> type, T target) throws GameException {

            IPersistService service = ServiceFactory
                    .getService(IPersistService.class);

            IPersister<T> p = service.getPersister(type);
            if (p == null) {
                throw new IllegalArgumentException(type.getName()
                        + " is not persistable");
            }

            p.setTarget(target);
            INode node = service.save(type, p);

            INodeXMLConverter converter = new ServerConverter();
            String data = converter.convertToXml(node);

            return data;
        }

    }

    private static Service service = new Service();

    public static Service service() {
        return ServerSerializerService.service;
    }

    private ServerSerializerService() {
        //
    }

}
